package com.dunqi.gpm.cangxi.home.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.PhotoPreviewActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.foamtrace.photopicker.intent.PhotoPreviewIntent;
import com.nanchen.compresshelper.CompressHelper;
import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.common.api.ApiFactory;
import com.dunqi.gpm.cangxi.common.api.RxSchedulers;
import com.dunqi.gpm.cangxi.common.base.BaseAct;
import com.dunqi.gpm.cangxi.common.base.Data;
import com.dunqi.gpm.cangxi.common.util.CommonUtil;
import com.dunqi.gpm.cangxi.common.util.FormUtil;
import com.dunqi.gpm.cangxi.common.util.JsonUtils;
import com.dunqi.gpm.cangxi.common.util.RequestBodyUtil;
import com.dunqi.gpm.cangxi.common.util.TimeUtil;
import com.dunqi.gpm.cangxi.common.view.ComTitleBar;
import com.dunqi.gpm.cangxi.common.view.NoScrollGridView;
import com.dunqi.gpm.cangxi.home.adapter.PhotoAdapter;
import com.dunqi.gpm.cangxi.home.bean.KnotComment;
import com.dunqi.gpm.cangxi.home.constance.Constance;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;

public class KnotCommentActivity extends BaseAct implements AdapterView.OnItemClickListener {


    private static final int REQUEST_CAMERA_CODE = 123;
    private static final int REQUEST_PREVIEW_CODE = 546;
    private static String KNOTCOMMENT = "knotcomment";
    @BindView(R.id.title_bar)
    ComTitleBar titleBar;
    @BindView(R.id.not_comment_1)
    RadioButton notComment1;
    @BindView(R.id.a)
    RadioButton a;
    @BindView(R.id.b)
    RadioButton b;
    @BindView(R.id.c)
    RadioButton c;
    @BindView(R.id.d)
    RadioButton d;
    @BindView(R.id.not_comment_2)
    RadioButton notComment2;
    @BindView(R.id.point_5)
    RadioButton point5;
    @BindView(R.id.point_4)
    RadioButton point4;
    @BindView(R.id.point_3)
    RadioButton point3;
    @BindView(R.id.point_2)
    RadioButton point2;
    @BindView(R.id.point_1)
    RadioButton point1;
    @BindView(R.id.grid_view)
    NoScrollGridView gridView;
    @BindView(R.id.radio_group1)
    RadioGroup radioGroup1;
    @BindView(R.id.radio_group2)
    RadioGroup radioGroup2;
    @BindView(R.id.commit_tv)
    TextView commitTv;
    @BindView(R.id.msg_edit)
    EditText msgEdit;

    ArrayList<String> data = new ArrayList<>();
    private PhotoAdapter adapter;
    private KnotComment item;

    ArrayList<RadioButton> evaluationGrades = new ArrayList<>();
    String[] evaluationGradeIndexs = {"excellent", "good", "medium", "poor"};

    ArrayList<RadioButton> evaluationScopes = new ArrayList<>();
    // 长传时间格式  yyyy-MM-dd HH:mm:ss

    @Override
    protected void refreshData(Bundle savedInstanceState) {

    }

    @Override
    protected void initUiAndListener() {

        item = (KnotComment) getIntent().getSerializableExtra(KNOTCOMMENT);
        titleBar.setTitle(item.getProjectName());

        data.add(null);

        adapter = new PhotoAdapter(getActivity(), data);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(this);


        evaluationGrades.add(a);
        evaluationGrades.add(b);
        evaluationGrades.add(c);
        evaluationGrades.add(d);

        evaluationScopes.add(point1);
        evaluationScopes.add(point2);
        evaluationScopes.add(point3);
        evaluationScopes.add(point4);
        evaluationScopes.add(point5);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String path = data.get(position);

        if (TextUtils.isEmpty(path)) {
            //
            PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true); // 是否显示拍照， 默认false
            intent.setMaxTotal(Constance.MAX_PIC); // 最多选择照片数量，默认为9
            ArrayList<String> paths = getPhotos();
            intent.setSelectedPaths(paths); // 已选中的照片地址， 用于回显选中状态
            // intent.setImageConfig(config);
            startActivityForResult(intent, REQUEST_CAMERA_CODE);
        } else {
            PhotoPreviewIntent intent = new PhotoPreviewIntent(getActivity());
            intent.setCurrentItem(position - 1); // 当前选中照片的下标
            ArrayList<String> paths = getPhotos();
            intent.setPhotoPaths(paths); // 已选中的照片地址
            startActivityForResult(intent, REQUEST_PREVIEW_CODE);
        }
    }

    @NonNull
    private ArrayList<String> getPhotos() {
        ArrayList<String> paths = new ArrayList<>();
        paths.addAll(data);
        paths.remove(0);
        return paths;
    }

    @OnClick({R.id.not_comment_1, R.id.a, R.id.b, R.id.c, R.id.d, R.id.not_comment_2, R.id.point_5, R.id.point_4, R.id.point_3, R.id.point_2, R.id.point_1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.not_comment_1:
                a.setChecked(false);
                b.setChecked(false);
                c.setChecked(false);
                d.setChecked(false);
                break;
            case R.id.a:
            case R.id.b:
            case R.id.c:
            case R.id.d:
                notComment1.setChecked(false);
                break;
            case R.id.not_comment_2:
                point1.setChecked(false);
                point2.setChecked(false);
                point3.setChecked(false);
                point4.setChecked(false);
                point5.setChecked(false);
                break;
            case R.id.point_5:
            case R.id.point_4:
            case R.id.point_3:
            case R.id.point_2:
            case R.id.point_1:
                notComment2.setChecked(false);
                break;
        }
    }

    public String getContent() {
        return msgEdit.getText().toString().trim();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_knot_comment;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    refreshAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                    break;
//                // 拍照
//                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
//                    if(captureManager.getCurrentPhotoPath() != null) {
//                        captureManager.galleryAddPic();
//                        // 照片地址
//                        String imagePaht = captureManager.getCurrentPhotoPath();
//                        // ...
//                    }
//                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    refreshAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));
                    break;
//            }
            }
        }
    }

    private void refreshAdpater(ArrayList<String> paths) {
        // 处理返回照片地址
        data.clear();
        data.add(null);
        data.addAll(paths);
        adapter.notifyDataSetChanged();
    }

    @OnClick(R.id.commit_tv)
    public void onViewClicked() {

        if (item == null) {
            return;
        }
        ArrayList<String> photos = getPhotos();

        HashMap<String, RequestBody> param = new HashMap<>();

        String[] remarks = new String[photos.size()];
        HashMap<String, String> paramString = new HashMap<>();

        for (String photo : photos) {
            File newFile = CompressHelper.getDefault(this)
                    .compressToFile(new File(photo));
            remarks[photos.indexOf(photo)] = photo;
            param.put("uploadFile\"; filename=\"" + newFile.getName(),
                    RequestBodyUtil.get(newFile));
        }

        paramString.put("projectId", String.valueOf(item.getProjectId()));

        paramString.put("proAnnualPlanId", String.valueOf(item.getProAnnualPlanId()));

        paramString.put("projectCloseDesc", msgEdit.getText().toString().trim());

        for (int i = 0; i < evaluationGrades.size(); i++) {
            RadioButton radioButton = evaluationGrades.get(i);
            if (radioButton.isChecked()) {
                paramString.put("evaluationGrade", evaluationGradeIndexs[i]);
            }
        }

        for (int i = 0; i < evaluationScopes.size(); i++) {
            RadioButton radioButton = evaluationScopes.get(i);
            if (radioButton.isChecked()) {
                paramString.put("evaluationScope", String.valueOf(i));
            }
        }

        paramString.put("projectCloseDate", TimeUtil.getCurrentTime());

        if (remarks.length != 0) {
            paramString.put("uploadFileRemark", JsonUtils.toJson(remarks));
        }

        paramString.put("proPlanProgressId", String.valueOf(item.getRelatedDataId()));

        FormUtil.AddHeader(paramString);

        for (Map.Entry<String, String> stringStringEntry : paramString.entrySet()) {
            param.put(stringStringEntry.getKey(),
                    RequestBodyUtil.get(stringStringEntry.getValue()));
        }



        final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在评论");

        ApiFactory.getInstance()
                .submitProjectCloseEval(param)
                .compose(RxSchedulers.<Data>io_main())
                .subscribe(new Consumer<Data>() {
                    @Override
                    public void accept(Data data) throws Exception {
                        finish();
                        CommonUtil.showSingleToast("评价成功");
                        dialog.dismiss();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        CommonUtil.showSingleToast("评价失败");
                        dialog.dismiss();
                    }
                });


    }

    public static void start(Activity context, KnotComment knotComment) {
        Intent intent = new Intent(context, KnotCommentActivity.class);
        intent.putExtra(KNOTCOMMENT, knotComment);
        context.startActivityForResult(intent, 132);
    }
}
